
export default class ProtocolMgr {

    private static inst:ProtocolMgr = null;

    public static get Inst():ProtocolMgr{
        if(!this.inst)this.inst = new ProtocolMgr();
        return this.inst;
    }

    httpStr:string = "https://kayingjia.v7.idcfengye.com";
    token:string = "";

    
    // 浏览器登录
    browserLogin() {
        this.sendHttp(this.httpStr + "/user/browser_login", 'post', null,
            (res) => {
                let obj:any = res;
                this.token = obj.token;
                
                let data = { token: this.token }
                console.log('*登录成功：', data);
                
                this.requestInfo(data);

            }, (res) => {
                console.log('*登录失败：', res);
            })
    }

    //请求用户表
    requestInfo(data:any){
        this.sendHttp(this.httpStr + "/user/info", 'post', data,
            (res) => {
                console.log(' info 请求成功：', res);
                let obj:any = res;
                let _json = obj.data;

                //StorageMgr.Inst.jsonObj = _json;
                console.log(_json);
            }, (res) => {
                console.log(' info 请求失败：', res);
            })
    }

    //请求更新分数
    request_updateScore(data:any){
        this.sendHttp(this.httpStr + "/user/score_update", 'post', data,
            (res) => {
                console.log(' score_update： 请求成功：', res);
            }, (res) => {
                console.log(' score_update： 请求失败：', res);
            })
    }
    
    //请求排行榜
    request_Ranking(){
        let data = { token: this.token }
        this.sendHttp(this.httpStr + "/user/...", 'post', data,
            (res) => {
                console.log('*请求成功：', res);


            }, (res) => {
                console.log('*请求失败：', res);
            })
    }

    
    //请求排行榜
    request_Level_info(data:any,call:Function,callLose:Function){
        console.log("*发送请求:" , data);
        this.sendHttp(this.httpStr + "/user/find_level", 'post', data,
            (res) => {
                console.log('*** 请求成功 level：', res);
                let obj:any = res;
                call(obj);

            }, (res) => {
                console.log('*** 请求失败 level：', res);
                callLose(res);
            })
    }



    //------------------------------------------------------------------------------------------



    /***
     * 发送http条文
     * @param url  路径
     * @param method 提交方式 GET POST
     * @param params 参数对象
     * @param successCallback 提交成功
     * @param errorCallback 提交失败
     * @param async 是否异步 - 默认 true
     */
    sendHttp<T>(url: string,
                        method: string,
                        params: object,
                        successCallback: (res: T) => void,
                        errorCallback?: (res: any) => void,
                        async = true) {
        let data = null;
        if (params) {
            //
            for (let k in params) {
                let v = params[k];
                if (data == null) {
                    data = `${k}=${v}`;
                } else {
                    data += `&${k}=${v}`;
                }
            }
            //
        }
        let xhr = new XMLHttpRequest();
        xhr.timeout = 10000;
        xhr.onreadystatechange = () => {
            if (xhr.readyState == XMLHttpRequest.DONE) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    let response = xhr.response;
                    try {
                        this.onHttpDone(response, (res) => {
                            switch (typeof res) {
                                case "object": {
                                    successCallback(<T>res);
                                    break;
                                }
                                case "string": {
                                    successCallback(<T>res);
                                    break;
                                }
                            }
                        }, errorCallback, xhr);
                    } catch (e) {
                        console.warn('运行后端回执引发的异常', response, e);
                        errorCallback && errorCallback(null);
                    }
                } else {
                    errorCallback && errorCallback(null);
                }
            }
        };
        xhr.ontimeout = () => {
            console.error('请求超时', url);
            errorCallback && errorCallback({code: -1, msg: '请求超时', data: null});
        }
        if (method.toUpperCase() == 'GET' && data) {
            url += `?${data}`;
        }

        xhr.open(method, url, async);
        xhr.responseType = 'json';
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');//xhr.setRequestHeader('Content-type', 'application/json');
        if (method.toUpperCase() == 'POST') {
            xhr.send(data);//JSON.stringify(params)
        } else {
            xhr.send();
        }
    }

    /**
     * @param {HttpData} jsonResponse
     * */
    private onHttpDone(jsonResponse: any, successCallback: (res: any | string) => void, errorCallback: (res: any) => void, xhr: XMLHttpRequest) {
        let {code, msg, data} = jsonResponse;

        if (code != null && code != 0) {
            errorCallback && errorCallback(jsonResponse);
            console.error('错误的回执', jsonResponse);
            return;
        }
        //
        successCallback(data || jsonResponse);
    }

    /**在区间内获取一个随机值*/
    getRandNumByArea(area:[number,number]){
        let maxNum = Math.max(...area);
        let minNum = Math.min(...area);
        let num = Math.random() * (maxNum - minNum) + minNum;
        return num;
    }

}

